package com.czt.mail.config;

import com.czt.mail.jwt.JWTUtils;
import com.google.gson.JsonObject;
import io.jsonwebtoken.JwtParser;
import lombok.extern.slf4j.Slf4j;
import org.codehaus.jettison.json.JSONObject;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author czt
 * @version 1.0
 * {@desc}
 * @date 2024/8/23 13:41
 */
@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    //在controller方法执行前执行,true放行，false，不放行
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("拦截器preHandle执行了");
        String url = request.getRequestURL().toString();
        if (url.contains("login")) {
            return true;
        }
        String jwt = request.getHeader("token");
        if (!StringUtils.hasLength(jwt)) {
            response.getWriter().write("请求头为空");
            return false;
        }
        JWTUtils.parseJWT(jwt);

        return true;
    }

    //目标资源方法执行后执行
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("拦截器postHandle执行了");
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    //视图渲染完毕后执行
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("拦截器afterCompletion执行了");
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
